import logging
import os
from datetime import datetime
from pathlib import Path
from typing import Optional

class TestLogger:
    """测试日志管理器"""
    
    _instance: Optional['TestLogger'] = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self._setup_logger()
            self._initialized = True
    
    def _setup_logger(self):
        """配置日志系统"""
        # 创建logs目录
        self.log_dir = Path("logs")
        self.log_dir.mkdir(exist_ok=True)
        
        # 配置根日志记录器
        self.root_logger = logging.getLogger()
        self.root_logger.setLevel(logging.INFO)
        
        # 清除现有的处理器
        self.root_logger.handlers.clear()
        
        # 创建文件处理器
        log_file = self.log_dir / f"test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.INFO)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 添加处理器
        self.root_logger.addHandler(file_handler)
        self.root_logger.addHandler(console_handler)
        
        # 创建测试日志记录器
        self.test_logger = logging.getLogger("test")
        self.test_logger.setLevel(logging.INFO)
    
    def get_logger(self, name: str) -> logging.Logger:
        """获取指定名称的日志记录器"""
        return logging.getLogger(name)
    
    def set_level(self, level: int):
        """设置日志级别"""
        self.root_logger.setLevel(level)
        self.test_logger.setLevel(level)
    
    def add_file_handler(self, filename: str, level: int = logging.INFO):
        """添加文件处理器"""
        log_file = self.log_dir / filename
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(level)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        self.root_logger.addHandler(file_handler)
    
    def clear_handlers(self):
        """清除所有处理器"""
        self.root_logger.handlers.clear()
        self._setup_logger()

# 创建全局日志管理器实例
test_logger = TestLogger() 